#!/bin/sh
#
# pfSense-rc
#
# part of pfSense (https://www.pfsense.org)
# Copyright (c) 2004-2013 BSD Perimeter
# Copyright (c) 2013-2016 Electric Sheep Fencing
# Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
# All rights reserved.
#
# originally based on m0n0wall (http://neon1.net/m0n0wall)
# Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#/bin/stty status '^T'
#/bin/stty susp '^-' intr '^-' quit '^-'

#trap : 2
#trap : 3

HOME=/
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin
export HOME PATH

get_version ()
{
	# Set our current version
	version=`/bin/cat /etc/version`

	# Version patch
	version_patch="0"
	if [ -f /etc/version.patch ]; then
		version_patch=`/bin/cat /etc/version.patch`
	fi

	if [ "${version_patch}" = "0" ]; then
		version_patch=""
	else
		version_patch=" (Patch ${version_patch})"
	fi
}

get_version

# Read product_name from $g, defaults to pfSense
# Use php -n here because we are not ready to load extensions yet
product_name=$(/usr/local/bin/php -n /usr/local/sbin/read_global_var product_name pfSense)
product_label=$(/usr/local/bin/php -n /usr/local/sbin/read_global_var product_label pfSense)

# Setup dumpdev/ddb/savecore"
echo "Configuring crash dumps..."
/etc/rc.dumpon

if [ -e /root/force_growfs ]; then
	/sbin/gpart show mmcsd0 2> /dev/null | grep -q freebsd-zfs
	if [ $? -eq 0 ]; then
		/sbin/zpool status pfSense | grep -q mmcsd0 > /dev/null
		if [ $? -eq 0 ]; then
			echo "Clearing ZFS label before expanding"
			/sbin/zpool labelclear /dev/mmcsd0
		fi
	fi
	/etc/rc.d/growfs onestart
fi

#
# The file system needs to be unmounted to guarantee a clean operation of fsck.
# Pending changes can keep the file system dirty until all the cached data is
# flushed to the disk.
#
/sbin/mount -ur /

fsck_forced_iterations=`/bin/kenv -q pfsense.fsck.force`
if [ ! -z "${fsck_forced_iterations}" ]; then
	echo "Forcing filesystem check (${fsck_forced_iterations} times)..."
	while [ ${fsck_forced_iterations} -gt 0 ]; do
		/sbin/fsck -fy -t ufs
		fsck_forced_iterations=$((fsck_forced_iterations - 1))
	done
fi

fsck_fix_flag_file="/.fix_for_SA-19-10.ufs"

# Apply fix for https://www.freebsd.org/security/advisories/FreeBSD-SA-19:10.ufs.asc
unset fsck_fix_applied
unset skip_fsck_fix
unset fsck_fix_count
if [ -f ${fsck_fix_flag_file} ]; then
	if ! awk '{print $3}' /etc/fstab | grep -q ufs; then
		echo "Fix for FreeBSD-SA-19:10.ufs is not needed in this system"
		skip_fsck_fix=1
	else
		fsck_fix_count=$(cat ${fsck_fix_flag_file})
		echo "Applying fix for FreeBSD-SA-19:10.ufs"
		/sbin/fsck -t ufs -f -p -T ufs:-z >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			fsck_fix_applied=1
		fi
	fi
fi

# Set it to 0 if it's empty
fsck_fix_count=${fsck_fix_count:-0}

FSCK_ACTION_NEEDED=0
/sbin/fsck -p
case $? in
0)
	echo "Filesystems are clean, continuing..."
	echo "Mounting filesystems..."
	;;
8|16)
	echo "Preen mode recommended running a check that will be performed now."
	FSCK_ACTION_NEEDED=1
	;;
*)
	echo "Stopping boot is recommended because filesystem manual action is needed, nevertheless automated repair of the filesystem will be attempted."
	FSCK_ACTION_NEEDED=1
	;;
esac

if [ ${FSCK_ACTION_NEEDED} = 1 ]; then
	echo "WARNING: Trying to recover filesystem from inconsistency..."
	/sbin/fsck -fy -t ufs
fi

/sbin/mount -a 2>/dev/null
mount_rc=$?
attempts=0
while [ ${mount_rc} -ne 0 -a ${attempts} -lt 10 ]; do
	/sbin/fsck -fy -t ufs
	/sbin/mount -a 2>/dev/null
	mount_rc=$?
	attempts=$((attempts+1))
done

if [ ${mount_rc} -ne 0 ]; then
	echo "ERROR: Impossible to mount filesystem, use interactive shell to attempt to recover it"
	/bin/sh
	/sbin/reboot
fi

. /etc/rc.ramdisk_functions.sh

# Handle ZFS read-only case
unset USE_ZFS
if /sbin/kldstat -qm zfs; then
	ZFSFSAVAILABLE=$(/sbin/zfs mount 2>/dev/null | wc -l)
	if [ $ZFSFSAVAILABLE -eq 0 ]; then
		/sbin/kldunload zfs
	else
		USE_ZFS=1
		ZFSROOT=$(/sbin/zfs mount | /usr/bin/awk '$2 == "/" {print $1}')
		if [ -n "$ZFSROOT" ]; then
			/sbin/zfs set readonly=off $ZFSROOT
		fi
		/sbin/zfs mount -a
		# If /bootpool is present, then there is an additional zfs pool to import
		# See https://redmine.pfsense.org/issues/8063
		if [ -d /bootpool ]; then
			/sbin/zpool import -f bootpool
		fi
		# We need to handle ZFS boot environments here
		_be_mount_zfs
	fi
fi

# If /conf is a directory, convert it to a symlink to /cf/conf
if [ -d "/conf" ]; then
	# If item is not a symlink then rm and recreate
	CONFPOINTSTO=`readlink /conf`
	if ! test "x$CONFPOINTSTO" = "x/cf/conf"; then
		/bin/rm -rf /conf
		/bin/ln -s /cf/conf /conf
	fi
fi

# Sanity check the clock
/etc/rc.checkclock

# Check if RAM disks are enabled, store for repeated use
if ramdisk_check_enabled; then
	USE_RAMDISK=true
fi

# Relocate pkgdb on UFS based on desired RAM disk settings
if [ -z "${USE_ZFS}" ]; then
	ramdisk_relocate_pkgdb_all
fi

# Dismount /tmp and /var on ZFS if using RAM disks and they are separate volumes
if [ -n "${USE_ZFS}" -a -n "${USE_RAMDISK}" ]; then
	ramdisk_fixup_zfs_unmount
fi

# Attempt to create and mount RAM disks
if [ -n "${USE_RAMDISK}" ]; then
	/etc/rc.embedded
	# Remount the correct subordinate ZFS datasets to ensure they are used properly
	if [ -n "${USE_ZFS}" ]; then
		_be_mount_zfs
	fi
fi

# If RAM disks are active, make symlinks for pkg database on UFS
if [ -n "${USE_RAMDISK}" -o -n "${MOVE_PKG_DATA}" ]; then
	if [ -z "${USE_ZFS}" ]; then
		ramdisk_link_pkgdb
	fi
fi

# If activating RAM disks failed, then undo some of the above actions
if [ -n "${USE_RAMDISK}" ] && ramdisk_failed; then
	ramdisk_fixup_zfs_mount
	if [ -z "${USE_ZFS}" ]; then
		ramdisk_relocate_pkgdb disk
	fi
else
	ramdisk_reset_status
fi

# Setup ddb on all platforms.
if [ ! -z "`sysctl -Nq debug.ddb.scripting.scripts`" ]; then
	/sbin/ddb /etc/${product_name}-ddb.conf
fi

# Restore contents of the RAM disk store
/etc/rc.restore_ramdisk_store

# Make sure /home exists
[ -d /home ] \
	|| mkdir /home

/bin/rm -f /root/force_fsck
/bin/rm -f /root/force_growfs
/bin/rm -f /root/TRIM_set
/bin/rm -f /root/TRIM_unset

# Disable APM on ATA drives. Leaving this on will kill drives long-term, especially laptop drives, by generating excessive Load Cycles.
if [ -f /etc/rc.disable_hdd_apm ]; then
	/etc/rc.disable_hdd_apm
fi

# Eject CD devices on 3G modems
MANUFACTURER="huawei|zte"
CDDEVICE=`dmesg |egrep -ie "($MANUFACTURER)" | awk -F: '/cd/ {print $1}'`
if [ "$CDDEVICE" != "" ]; then
	cdcontrol -f /dev/"$CDDEVICE" eject
fi

# Use php -n here because we are not ready to load extensions yet
varrunpath=$(/usr/local/bin/php -n /usr/local/sbin/read_global_var varrun_path "/var/run")

if ! ramdisk_is_active; then
	/sbin/mount -o rw,size=4m,mode=1777 -t tmpfs tmpfs $varrunpath
fi

echo
cat /usr/local/share/pfSense/ascii-art/pfsense-logo-small.txt
echo
echo
echo "Welcome to ${product_label} ${version}${version_patch}..."
echo

/sbin/conscontrol mute off >/dev/null

SWAPDEVICE=`/bin/cat /etc/fstab | /usr/bin/grep swap | /usr/bin/cut -f1 | /usr/bin/head -n 1`
if [ -n "${SWAPDEVICE}" ]; then
	/bin/rm -f /tmp/fstab.swap
	if ! [ -c ${SWAPDEVICE} ]; then
		# Keep the original device, in case it is special, such as encrypted+mirrored zfs swap
		echo "${SWAPDEVICE}	none	swap	sw	0	0" >> /tmp/fstab.swap
		# The swap device in fstab does not exist, look for other valid entries and update fstab
		for SWAPLABEL in /dev/label/swap* /dev/mirror/swap*; do
			if [ -c ${SWAPLABEL} ]; then
				echo "${SWAPLABEL}	none	swap	sw	0	0" >> /tmp/fstab.swap
			fi
		done
	else
		/bin/cp /etc/fstab /tmp/fstab.swap
	fi
	/sbin/swapon -F /tmp/fstab.swap -a 2>/dev/null >/dev/null
	/etc/rc.savecore
fi

# make some directories in /var
/bin/mkdir -p $varrunpath /var/log /var/etc /var/db/entropy /var/db/rrd /var/at/jobs/ /var/empty /var/log/nginx 2>/dev/null

# turn off the immutable flag, set /var/empty to read-only, make it immutable again
chflags noschg /var/empty
chmod 0555 /var/empty
chflags schg /var/empty

/bin/rm -rf $varrunpath/*

# Cleanup configuration files from previous instance
/bin/rm -rf /var/etc/*

# Workaround for ipsec symlinks, otherwise it's going to break
# strongswan pkg upgrade

if [ -L /usr/local/etc/ipsec.d ]; then
	rm -f /usr/local/etc/ipsec.d
fi
if [ -L /usr/local/etc/ipsec.conf ]; then
	rm -f /usr/local/etc/ipsec.conf
fi
if [ -L /usr/local/etc/strongswan.d ]; then
	rm -f /usr/local/etc/strongswan.d
fi
if [ -L /usr/local/etc/strongswan.conf ]; then
	rm -f /usr/local/etc/strongswan.conf
fi

# Remove deprecated symlinks - #5538
for f in /etc/hosts \
    /etc/resolv.conf \
    /etc/resolvconf.conf \
    /etc/syslog.conf; do
	if [ -L "${f}" ]; then
		rm -f ${f}
	fi
done

# Make sure our /tmp is 777 + Sticky
/bin/chmod 1777 /tmp

if [ ! -L /etc/dhclient.conf ]; then
	/bin/rm -rf /etc/dhclient.conf
fi

if [ ! -d /var/tmp ]; then
	/bin/mkdir -p /var/tmp
fi
# Make sure our /var/tmp is 777 + Sticky
/bin/chmod 1777 /var/tmp

set -T
trap "echo 'Reboot interrupted'; exit 1" 3

echo -n "."
LOG_FILES="system filter dhcpd vpn poes l2tps openvpn auth portalauth ipsec ppp wireless nginx ntpd gateways resolver routing"

for logfile in $LOG_FILES; do
	/usr/bin/touch /var/log/${logfile}.log
done

# change permissions on newly created log files.
/bin/chmod 0600 /var/log/*.log

echo -n "."
DEVFS=`/sbin/mount | /usr/bin/grep devfs | /usr/bin/wc -l | /usr/bin/cut -d" " -f8`
if [ "$DEVFS" = "0" ]; then
	mount_devfs devfs /dev
fi

# Create an initial utmp file
cd $varrunpath && /bin/cp /dev/null utmp && /bin/chmod 644 utmp

echo -n "."
/sbin/ldconfig -elf /usr/lib /usr/local/lib /lib
/etc/rc.d/ldconfig start 2>/dev/null

# Launching kbdmux(4)
if [ -f "/dev/kbdmux0" ]; then
	echo -n "."
	/usr/sbin/kbdcontrol -k /dev/kbdmux0 < /dev/console
	[ -c "/dev/atkbd0" ] && kbdcontrol -a atkbd0 < /dev/console
	[ -c "/dev/ukbd0" ] && kbdcontrol -a ukbd0 < /dev/console
fi

# Fire up unionfs if mount points exist.
if [ -f /dist/uniondirs ]; then
	echo -n "."
	/etc/rc.d/unionfs start
fi

echo "done."

# Recreate capabilities DB
/usr/bin/cap_mkdb /etc/login.conf

if [ -f /cf/conf/needs_package_sync ]; then
	skip_packages=1
fi

# Second upgrade stage
[ -z "$skip_packages" ] \
	&& /usr/local/sbin/${product_name}-upgrade -y -U -b 2

# Copy default openssl config file and Netgate CA
[ -d /etc/ssl ] \
	|| mkdir -p /etc/ssl
[ -f /usr/local/share/${product_name}/ssl/openssl.cnf ] \
	&& cp -f /usr/local/share/${product_name}/ssl/openssl.cnf /etc/ssl
mkdir -p /usr/local/openssl >/dev/null 2>&1
ln -sf /etc/ssl/openssl.cnf \
	/usr/local/openssl/openssl.cnf

[ -f /usr/local/share/${product_name}/ssl/netgate-ca.pem ] \
	&& cp -f /usr/local/share/${product_name}/ssl/netgate-ca.pem /etc/ssl

# Run the php.ini setup file and populate
# /usr/local/etc/php.ini
/etc/rc.php_ini_setup 2>/tmp/php_errors.txt
/usr/local/sbin/php-fpm -c /usr/local/etc/php.ini -y /usr/local/lib/php-fpm.conf -RD 2>&1 >/dev/null

# Launch external configuration loader
/etc/rc.ecl

if [ -f /etc/rc.custom_boot_early ]; then
	/bin/echo -n "Launching /etc/rc.custom_boot_early...";
	/etc/rc.custom_boot_early
	echo "Done"
fi

export fcgipath=/var/run/php-fpm.socket
/usr/bin/nice -n20 /usr/local/sbin/check_reload_status

# let the PHP-based configuration subsystem set up the system now
echo -n "Launching the init system..."
/bin/rm -f /cf/conf/backup/backup.cache
/usr/bin/touch $varrunpath/booting

# Copy custom logo over if it's present
if [ -d /usr/local/share/${product_name}/custom_logos ]; then
	cp -f /usr/local/share/${product_name}/custom_logos/*svg \
		/usr/local/www
	cp -f /usr/local/share/${product_name}/custom_logos/*css \
		/usr/local/www/css
fi

# Apply CPU microcode update
[ -x /usr/local/etc/rc.d/microcode_update ] \
	&& /usr/local/etc/rc.d/microcode_update onestart

if [ -n "${skip_fsck_fix}" ]; then
	rm -f ${fsck_fix_flag_file}
elif [ -f ${fsck_fix_flag_file} ]; then
	# fsck fix already applied
	if [ -n "${fsck_fix_applied}" ]; then
		touch /cf/conf/applied_fix_for_SA-19-10.ufs
		rm -f ${fsck_fix_flag_file}
	elif [ ${fsck_fix_count} -ge 3 ]; then
		echo "ERROR: fsck fix for SA-19-10 failed to apply..."
		sleep 5
		rm -f ${fsck_fix_flag_file}
	else
		# if / is UFS, reroot instead of reboot
		root_fstype=$(mount -p / | awk '{print $3}')
		unset reroot
		if [ "${root_fstype}" = "ufs" ]; then
			reroot="-r"
		fi

		# fsck fix failed, increment escape counter to avoid infinite
		# loop on a system with a broken filesystem
		fsck_fix_count=$((fsck_fix_count+1))

		echo "${fsck_fix_count}" > ${fsck_fix_flag_file}

		# fsck binary was old and didn't have -z option, then reboot
		# and run again
		echo "fsck needs to run to fix SA-10-10. Rebooting..."
		/etc/rc.reboot ${reroot}
		exit 0
	fi
fi

/etc/rc.bootup

# /etc/rc.bootup unset $g['booting'], and removes file
# Be sure the file is removed to not create troubles after
if [ -f $varrunpath/booting ]; then
	/bin/rm $varrunpath/booting
fi

if [ -n "${USE_ZFS}" ]; then
	# Create ZFS reservation
	if [ ! -f /.no_zfs_reservation ]; then
		zpool list -o name pfSense > /dev/null 2>&1 && ZPOOL=pfSense
		zpool list -o name zroot > /dev/null 2>&1 && ZPOOL=zroot
		if [ -n "${ZPOOL}" ]; then
			zfs list -Hp -o name -t filesystem | grep -q ${ZPOOL}/reservation
			if [ $? -ne 0 ]; then
				AVAIL=$( zfs list -Hpo avail ${ZPOOL} )
				RESSIZE=$( zfs list -Hpo avail,used ${ZPOOL} | awk -v CONVFMT='%.0f' '{printf ( $1 + $2 ) * 0.1 "\n"}' )
				if [ $(( ${AVAIL} / 2 )) -gt ${RESSIZE} ]; then
					logger "Creating ZFS reservation of ${RESSIZE} bytes on ${ZPOOL}"
					zfs create -o reservation=${RESSIZE} ${ZPOOL}/reservation
				else
					logger "Not enough space to create reservation on ${ZPOOL};  ${AVAIL} / 2 is not greater than ${RESSIZE} bytes"
				fi
			fi
		fi
	fi

	# Enable zpool trimming
	if [ ! -f /.no_zpool_autotrim ]; then
		/sbin/zpool list -o name pfSense > /dev/null 2>&1 && ZPOOL=pfSense
		/sbin/zpool list -o name zroot > /dev/null 2>&1 && ZPOOL=zroot
		if [ -n "${ZPOOL}" ]; then
			AUTOTRIM=$( /sbin/zpool get -H -o value autotrim "${ZPOOL}" )
			if [ "${AUTOTRIM}" = "off" ]; then
				echo -n "Trimming the zpool... "
				/sbin/zpool set autotrim=on "${ZPOOL}"
				/sbin/zpool trim "${ZPOOL}"
				echo "done."
			fi
		fi
	fi
fi

echo -n "Starting CRON... "
cd /tmp && /usr/sbin/cron -s 2>/dev/null
echo "done."

/bin/rm -rf /usr/local/pkg/pf/CVS

# Start ping handler every 240 seconds
/usr/local/bin/minicron 240 $varrunpath/ping_hosts.pid /usr/local/bin/ping_hosts.sh

# Start IPsec keep alive handler every 300 seconds
/usr/local/bin/minicron 300 $varrunpath/ipsec_keepalive.pid /usr/local/bin/ipsec_keepalive.php

# Start account expire handler every hour
/usr/local/bin/minicron 3600 $varrunpath/expire_accounts.pid '/usr/local/sbin/fcgicli -f /etc/rc.expireaccounts'

# Start alias url updater every 24 hours
/usr/local/bin/minicron 86400 $varrunpath/update_alias_url_data.pid '/usr/local/sbin/fcgicli -f /etc/rc.update_alias_url_data'

/bin/chmod a+rw /tmp/.

# Check for GEOM mirrors
GMIRROR_STATUS=`/sbin/gmirror status`
if [ "${GMIRROR_STATUS}" != "" ]; then
	# Using a flag file at bootup saves an expensive exec/check on each page load.
	/usr/bin/touch /var/run/gmirror_active
	# Setup monitoring/notifications
	/usr/local/bin/minicron 60 /var/run/gmirror_status_check.pid /usr/local/sbin/gmirror_status_check.php
fi

[ -z "$skip_packages" ] \
	&& /usr/local/sbin/${product_name}-upgrade -y -U -b 3

# Start packages
[ -z "$skip_packages" ] \
	&& /usr/local/sbin/fcgicli -f /etc/rc.start_packages

# Update pkg metadata
/etc/rc.update_pkg_metadata now

# Log product version to syslog
get_version
BUILDTIME=`cat /etc/version.buildtime`
ARCH=`uname -m`
echo "$product_label ${version}${version_patch} $ARCH $BUILDTIME"

echo "Bootup complete"
echo "Bootup complete" | /usr/bin/logger

/usr/local/bin/beep.sh start 2>&1 >/dev/null

# Reset the cache.  read-only requires this.
/bin/rm -f /tmp/config.cache

exit 0
